using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using HappySprite;
using System.Collections;

namespace HappyInvaders
{
    class Presenter
    {
        Model model;
        View view;

        public Presenter(Model model, View view)
        {
            this.model = model;
            this.view = view;

            Bind();
        }

        public void Draw()
        {
            // Draw the view
            view.Draw();
        }

        public void Update(GameTime gameTime)
        {
            // Update lives and score
            view.Lives = model.Lives;
            view.Score = model.Score;

            // Show game over
            view.ShowGameOver = model.GameOver;

            // Check for player pressing fire
            if (model.GameOver)
            {
                PlayerInput playerInput = view.GetPlayerInput();

                if (playerInput.Fire)
                {
                    model.Lives = 3;
                    model.Score = 0;
                    model.StartLevel(1);
                    playerInput.Fire = false;
                }
            }

            // Update the model
            model.Update(gameTime);
        }

        void Bind()
        {
            // Bind player input
            model.SetPlayerInput(view.GetPlayerInput());

            // Bind entity created event
            model.EntityCreated += delegate(Entity entity)
            {
                Visual visual = VisualFactory(entity);
                visual.SetPosition(entity.Position);

                entity.PositionChanged += visual.SetPosition;
                entity.Removed += visual.Remove;
                entity.TextureChanged += visual.SetTexture;
            };

            // Bind won event
            model.WonLevel += delegate()
            {
                model.StartLevel(model.Level + 1);
            };
        }

        Visual VisualFactory(Entity entity)
        {
            if (entity is BombEntity) return view.CreateBomb();
            if (entity is BulletEntity) return view.CreateBullet();
            if (entity is ExplosionEntity) return view.CreateExplosion();
            if (entity is PlayerEntity) return view.CreatePlayer();
            if (entity is SaucerEntity) return view.CreateSaucer();
            if (entity is ShelterEntity) return view.CreateShelter();
            if (entity is ZapEntity) return view.CreateZap();

            if (entity is InvaderEntity)
            {
                InvaderEntity invader = entity as InvaderEntity;
                return view.CreateInvader(invader.Row);
            }

            throw new InvalidOperationException("Unknown Entity.");
        }
    }
}
